<?php

namespace App\Admin\Actions\NewsAction;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use App\Supports\LinkedIn\Client;
use Illuminate\Support\Str;
use Intervention\Image\Gd\Font;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;
use GuzzleHttp\Client as GuzzleClient;


class linkedinPost extends RowAction
{
    public $name = 'linkedin发帖';
    
    public function handle(Model $model)
    {
	    /**
	     * @var $model User
	     */
    	
    	
	   	/*if ($model->linkedin_share_id) {
    		return $this->response()->success('已发过贴了');
	    }*/

	    //$image = $this->make($model);
	   
    	
    	DB::transaction(function () use ($model) {
    		//dd($model->getTableName());
    		$table = $model->getTableName();
    		if($table =='deep_news'){
    			$client = new Client(
				    getenv('LINKDIN_CLIENT_ID'),
				    getenv('LINKDIN_CLIENT_SECRET'),
				);
				$client->setRedirectUrl('https://www.xbreakingtechinsight.com');

				$user = User::find(1);
				
				$client->setAccessToken($user->linkdin_token);

				/* $linkedInClient = new GuzzleClient(['base_uri' => 'https://api.linkedin.com']);
				

				$response = $linkedInClient->post(
				        '/mediaUpload/C5522AQGTYER3k3ByHQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJbrN86Zm265gAAAWemyz2pxPSgONtBiZdchrgG872QltnfYjnMdb2j3A&app=1953784&sync=0&v=beta&ut=2H-IhpbfXrRow1', [
				            'headers' => [
				                'Accept'                => 'application/json',
				                'Authorization'         => 'Bearer '.$user->linkdin_token,
				            ],
				            'multipart' => [
				                [
				                    'name'     => 'upload-file',
				                    'contents' => file_get_contents($image),
				                ],
				            ],
				        ]
				    );
				$contents = json_decode($response->getBody()->getContents());

				dd($contents);*/
				/*$arr = [
					"registerUploadRequest"=>[
						"recipes"=>[
				            "urn:li:digitalmediaRecipe:feedshare-image"
				        ],
				        "owner"=> "urn:li:organization:100897090",
				        "serviceRelationships"=> [
				            [
				                "relationshipType": "OWNER",
				                "identifier": "urn:li:userGeneratedContent"
				            ]
				        ]
					]

				]*/
				$arr = [                                   
		                    'author' => 'urn:li:organization:100897090',
		                    'lifecycleState' => 'PUBLISHED',
		                    'specificContent' => [          
		                        'com.linkedin.ugc.ShareContent' => [
		                            'shareCommentary' => [
		                                'text' => $model->brief_zn
		                            ],
		                            'shareMediaCategory' => 'ARTICLE',
		                            'media' => [
		                                [
		                                    'status' => 'READY',
		                                    'description' => [
		                                        'text' => strip_tags($model->brief_zn)
		                                    ],
		                                    'thumbnails'=> [
		                                    	['url' => img_path($model->images)]
		                                    	
		                                    ],

		                                    //img_path($new['images']
		                                    'originalUrl' => "https://www.xbreakingtechinsight.com/detail/".$model->id,
		                                    'title' => [
		                                        'text' => $model->title_zn
		                                    ]
		                                ]
		                            ]
		                        ]
		                    ],
		                    'visibility' => [
		                        'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC'
		                    ]
		                ];

		               
				$share = $client->post(                 
		                'ugcPosts',                         
		                $arr
		            );

				

    			
    		}
    		

			$model->update([
			    'linkedin_share_id'=>$share['id'],
		    ]);


		   
	    });
    	
    	
	    return $this->response()->success('发帖成功')->refresh();
    }


    protected function getPosterName($cover)
	{
		return Str::random(40)."jpg";
	}
	
	protected function getRemotePosterDir($cover)
	{

		$dirname = dirname($cover);
		$dirname = str_replace('https://littleshop.oss-cn-beijing.aliyuncs.com/','',$dirname);
		return $dirname;
	}
	
	protected function getRemotePosterSavePath($cover)
	{
		return $this->getRemotePosterDir($cover) . '/' . $this->getPosterName($cover);
	}

	protected function getLocalPosterSavePath(string $name)
	{
		$localPath = public_path('temp/mini-product-thumbnail');
		if (! File::isDirectory($localPath)) {
			File::makeDirectory($localPath, 755, true, true);
		}
		return "{$localPath}/{$name}.jpg";
	}

    public function make($model)
	{
		
		/*if (Storage::exists($this->getRemotePosterSavePath($model->images))) {
			return Storage::url($this->getRemotePosterSavePath($model->images));
		}*/
		
		$posterDir = $this->getRemotePosterDir($model->images);
		$posterName = $this->getPosterName($model->images);
		

		
		$back = Image::make(public_path("/image/back.png"));



		$cover = Image::make(img_path($model->images));
		$width = $cover->width();
        $height = $cover->height();

        $nowHeight= $height/$width*1080;
        $cover->resize(1080,$nowHeight);

        $maxWidth=1000;
       /* if($width > $height * (1080/400)){
        	$maxWidth = 520;
        	$cover->resize(520,400);
        }else{
        	$maxWidth = 1080-$width/($height/400);
        	$cover->resize($width/($height/400),400);
        }*/

        $fontPath=public_path('font/Bevan-Regular.ttf');

         $characters = mb_str_split($model->title_zn); // 分割中文字符
         $lines = [];
         $currentLine = '';
         $fontSize = 40;
	    foreach ($characters as $char) {
	        $testLine = $currentLine . $char;
	        // 计算当前行的宽度
	        $box = imagettfbbox($fontSize, 0, $fontPath, $testLine);

	        $textWidth = $box[2] - $box[0];
	        if ($textWidth > $maxWidth) {
	            $lines[] = $currentLine;
	            $currentLine = $char;
	        } else {
	            $currentLine = $testLine;
	        }
	    }
	    $lines[] = $currentLine;
	    $lineHeight = $fontSize * 1.5;
	    

	    // 调整字体大小以适应高度
	    $totalHeight = count($lines) * $lineHeight;
	   /* while ($totalHeight > $maxHeight && $fontSize > 8) {
	        $fontSize--;
	        $lineHeight = $fontSize * 1.5;
	        $totalHeight = count($lines) * $lineHeight;
	    }*/
		
		$y1 = $nowHeight-$totalHeight-30;

		$img = Image::canvas(1080, $nowHeight, '#FFFFFF')
			//->insert($back, 'top', 0, 0)
			->insert($cover, 'top', 0, 0)
			->rectangle(0, $y1, 1080, $nowHeight, function($draw){  
                $draw->background('rgba(0, 0, 0, 0.5)');  
            }); 
		 $y = $nowHeight-$totalHeight+20;	
		 $currentY = $y;
		 $x = 60;
	     foreach ($lines as $line) {
	        $img->text($line, $x, $currentY, function ($font) use ($fontSize, $fontPath) {
	            $font->file($fontPath);
	            $font->size($fontSize);
	            $font->color('#FFFFFF'); // 文字颜色
	        });
	        $currentY += $lineHeight;
	     }

		$img->save($this->getLocalPosterSavePath($posterName));
		
		// move to oss.
		Storage::putFileAs($posterDir, $this->getLocalPosterSavePath($posterName), $posterName);
		
		// remove local poster.
		File::delete($this->getLocalPosterSavePath($posterName));
		
		return Storage::url("{$posterDir}/{$posterName}");
	}
	
	public function dialog()
	{
		$this->confirm('确定发帖到linkedin吗?');
	}
}
